<template>
  <div>
    <div class="jobs-container" v-infinite-scroll="loadMore">
      <!-- 左侧筛选区 -->
      <div class="filter-section">
        <div class="filter-header">
          <h3>职位筛选</h3>
        </div>
        <div class="filter-content">
          <div class="search-box">
            <h4>职位搜索</h4>
            <el-input v-model="name" placeholder="请输入关键词" :prefix-icon="Search" />
          </div>

          <div class="filter-box">
            <h4>工作经验</h4>
            <el-radio-group v-model="workExperience">
              <el-radio v-for="exp in experiences" :key="exp" :label="exp">
                {{ exp }}
              </el-radio>
            </el-radio-group>
          </div>

          <div class="filter-box">
            <h4>学历要求</h4>
            <el-radio-group v-model="education">
              <el-radio v-for="edu in educations" :key="edu" :label="edu">
                {{ edu }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <!-- 右侧职位列表 -->
      <div class="jobs-list">
        <div class="jobs-header">
          <h2>在招职位</h2>
          <div class="jobs-count">{{ total }} 个职位</div>
        </div>
        <div class="jobs-content" :infinite-scroll-disabled="loading">
          <div v-for="job in jobs" :key="job.id" class="job-item">
            <div class="job-main" @click="handleJobClick(job.id)">
              <h3 class="job-title">{{ job.name }}</h3>
              <div class="job-date">
                截止日期 {{ dayjs(job.deadline).format('YYYY-MM-DD') }}
                <el-popover placement="right" :width="200" trigger="click" @show="generateQRCode(job.id)" @click.stop>
                  <template #reference>
                    <el-button class="share-btn" type="primary" link :icon="Share" @click.stop></el-button>
                  </template>
                  <div class="share-content">
                    <img v-if="qrcodeUrls[job.id]" :src="qrcodeUrls[job.id]" class="qrcode-img" alt="分享二维码" />
                    <div class="share-link">
                      <el-input v-model="shareLinks[job.id]" size="small" readonly>
                        <template #append>
                          <el-button @click="copyLink(job.id)">复制</el-button>
                        </template>
                      </el-input>
                    </div>
                    <div class="share-tip">扫描二维码分享</div>
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
          <div v-if="loading" class="loading-text">加载中...</div>
          <div v-if="!hasMore && jobs.length > 0" class="no-more-text">没有更多数据了</div>
          <div v-if="jobs.length === 0" class="empty-text">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Share } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { selectSeekerPage } from '@/api/position'
import { myDebounce } from '@/utils/tools'
import { decrypt } from '@ruifox-cms/utils'
import QRCode from 'qrcode'
import dayjs from 'dayjs'

const router = useRouter()

// 定义学历和工作经验映射
const DEGREE_MAP = {
  '不限': '',
  '初中及以下': '1',
  '中专/中技': '2',
  '高中': '3',
  '大专': '4',
  '本科': '5',
  '硕士': '6',
  '博士': '7'
}

const EXPERIENCE_MAP = {
  '不限': '',
  '应届生': '1',
  '1-3年': '2',
  '3-5年': '3',
  '5年以上': '4'
}

// 筛选条件数据
const experiences = Object.keys(EXPERIENCE_MAP)
const educations = Object.keys(DEGREE_MAP)

// 响应式状态
const name = ref('')
const workExperience = ref('')
const education = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const jobs = ref([])
const initialLoad = ref(true)

// 获取职位列表
const fetchJobs = async (isLoadMore = false) => {
  if (loading.value) return
  if (!localStorage.getItem('recruitment-groupId')) {
    ElMessage.error('参数groupId缺失')
    jobs.value = []
    total.value = 0
    return
  }

  loading.value = true
  try {
    const params = {
      groupId: decrypt(localStorage.getItem('recruitment-groupId')),
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      name: name.value,
      degree: DEGREE_MAP[education.value],
      workExperience: workExperience.value ? EXPERIENCE_MAP[workExperience.value] : ''
    }

    const res = await selectSeekerPage(params)
    if (isLoadMore) {
      jobs.value.push(...res.data.list)
    } else {
      jobs.value = res.data.list
    }
    total.value = res.data.total
    hasMore.value = jobs.value.length < total.value
  } catch (error) {
    console.error('获取职位列表失败:', error)
    ElMessage.error('获取职位列表失败')
  } finally {
    loading.value = false
    initialLoad.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value || initialLoad.value) return
  currentPage.value++
  fetchJobs(true)
}

// 监听筛选条件变化
watch(
  [name, workExperience, education],
  myDebounce(() => {
    currentPage.value = 1
    hasMore.value = true
    fetchJobs()
  }, 500),
  { deep: true }
)

onMounted(() => {
  if (router.currentRoute.value.query.groupId) {
    localStorage.setItem('recruitment-groupId', router.currentRoute.value.query.groupId)
  }
  fetchJobs()
})

// 方法
const handleJobClick = jobId => {
  router.push(`/recruitment/user/apply?jobId=${jobId}`)
}

const qrcodeUrls = ref({})
const shareLinks = ref({})

const generateQRCode = async jobId => {
  const link = `${window.location.origin}${process.env.BASE_URL}recruitment/user/apply?jobId=${jobId}&groupId=${localStorage.getItem('recruitment-groupId')}`
  shareLinks.value[jobId] = link

  if (!qrcodeUrls.value[jobId]) {
    try {
      const url = await QRCode.toDataURL(link, {
        width: 120, // 减小二维码尺寸
        margin: 0,
        color: {
          dark: '#000',
          light: '#fff'
        }
      })
      qrcodeUrls.value[jobId] = url
    } catch (err) {
      console.error(err)
    }
  }
}

const copyLink = async jobId => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(shareLinks.value[jobId])
    } else {
      const textArea = document.createElement('textarea')
      textArea.value = shareLinks.value[jobId]
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    ElMessage.success('链接已复制')
  } catch (err) {
    console.error(err)
    ElMessage.error('复制失败')
  }
}
</script>

<style lang="scss" scoped>
.jobs-container {
  max-width: 1000px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
  height: 100%;
}

.filter-section {
  width: 240px;
  flex-shrink: 0;

  .filter-header {
    background: #fff;
    padding: 15px 20px;
    border-radius: 4px;
    margin-bottom: 1px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }
  }

  .filter-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
  }

  .filter-box {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #666;
    }
  }

  .search-box {
    margin-bottom: 24px;

    h4 {
      margin-bottom: 12px;
      font-size: 14px;
      color: #666;
    }
  }
  .el-radio-group .el-radio {
    margin-right: 8px;
  }
}

.jobs-list {
  flex-grow: 1;
  min-width: 0;

  .jobs-header {
    background: #fff;
    padding: 15px 20px;
    border-radius: 4px;
    margin-bottom: 1px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }

    .jobs-count {
      color: #666;
      font-size: 14px;
    }
  }

  .jobs-content {
    background: #fff;
    padding: 10px;
    border-radius: 4px;
    overflow-y: auto;
  }
}

.job-item {
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 4px;

  &:not(:last-child) {
    border-bottom: 1px solid #f0f0f0;
  }

  .job-main {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .job-title {
    margin: 0;
    font-size: 15px;
    font-weight: 500;
    color: #333;
    flex: 1;
    margin-right: 20px;
  }

  .job-date {
    color: #999;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
  }

  &:hover {
    background-color: #f5f7fa;
  }
}

.share-btn {
  padding: 0;
  height: auto;

  &:hover {
    color: #409eff;
  }
}

.share-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 8px;

  .qrcode-img {
    width: 120px; // 减小二维码尺寸
    height: 120px;
    display: block;
  }

  .share-link {
    width: 100%;
  }

  .share-tip {
    color: #909399;
    font-size: 12px;
  }
}

.loading-text,
.no-more-text,
.empty-text {
  text-align: center;
  color: #909399;
  padding: 16px 0;
  font-size: 14px;
}

@media (max-width: 768px) {
  .jobs-container {
    flex-direction: column;
    padding: 0 10px;
  }

  .filter-section {
    width: 100%;
    margin-bottom: 20px;
  }

  .job-item {
    padding: 15px;

    .job-main {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }

    .job-title {
      margin-right: 0;
    }
  }
}
</style>
